package com.online.pay.common.utils;

import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.xml.XMLSerializer;
import nu.xom.Document;

public class XmlJson {
	
	 /**
     * 将xml字符串<STRONG>转换</STRONG>为JSON字符串
     * 
     * @param xmlString
     *            xml字符串
     * @return JSON<STRONG>对象</STRONG>
     */
    public static String xml2json(String xmlString) {
        XMLSerializer xmlSerializer = new XMLSerializer();
        JSON json = xmlSerializer.read(xmlString);
        return json.toString(1);
    }

    /**
     * 将xmlDocument<STRONG>转换</STRONG>为JSON<STRONG>对象</STRONG>
     * 
     * @param xmlDocument
     *            XML Document
     * @return JSON<STRONG>对象</STRONG>
     */
    public static String xml2json(Document xmlDocument) {
        return xml2json(xmlDocument.toString());
    }

    /**
     * JSON(数组)字符串<STRONG>转换</STRONG>成XML字符串
     * 
     * @param jsonString
     * @return
     */
    public static String json2xml(String json) {
        XMLSerializer xmlSerializer = new XMLSerializer();
        //设置转换的xml的根元素名称
        xmlSerializer.setRootName("xml");
        //设置每个元素是否显示type属性
        xmlSerializer.setTypeHintsEnabled(false);
        String xmlStr = "";
        if (json.contains("[") && json.contains("]")) {
			JSONArray jsonArray = JSONArray.fromObject(json);
			xmlStr = xmlSerializer.write(jsonArray);
		} else {
			JSONObject jsonObject = JSONObject.fromObject(json);
			xmlStr = xmlSerializer.write(jsonObject);
		}
        return xmlStr;
    }
    
}
